<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测数据管理
 */
namespace app\admin\service;

use app\common\model\ChargingModel;
use app\common\model\DetectionModel;
use app\common\model\OrderModel;
use app\common\model\OrderProjectModel;
use app\common\model\ProjectModel;
use think\Collection;
use think\Db;

class DetectionService
{
    protected static $model;
    protected static $order;
    protected static $project;
    protected static $charge;
    protected static $orderProject;

    /**
     * InstrumentService constructor.
     * @param DetectionModel $detectionModel
     * @author zws
     */

    public function __construct(
        DetectionModel $detectionModel,
        OrderProjectModel $orderProjectModel,
        ProjectModel $projectModel,
        ChargingModel $chargingModel,
        OrderModel $orderModel
    )
    {
        self::$model = $detectionModel;
        self::$orderProject = $orderProjectModel;
        self::$project = $projectModel;
        self::$charge = $chargingModel;
        self::$order = $orderModel;
    }

    /**
     * 检测数据列表
     * @param $param
     * @return array|\PDOStatement|string|\think\Collection
     * @author zws
     */
    public function index($param)
    {
        if(!isset($param['page']) || empty($param['page'])){
            $param['page'] = 1;
        }
        if(!isset($param['limit']) || empty($param['limit'])){
            $param['limit'] = 10;
        }
        $where = '';
        if ($param['order_id']) {
            $where = ['order_id' => $param['order_id']];
        }
        // 获取总数
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => $count];
        }
        $projectData = $this->getParentProject();
        $result = self::$model->where($where)
            ->page($param['page'], $param['limit'])
            ->order('create_time', 'desc')
            ->select();
        $result->map(function (&$item) use ($projectData) {
            if($item->project_id){
                $item->project;
                if(isset($projectData[$item->project->pid])){
                    $item->project_type = $projectData[$item->project->pid]['project_name'];
                }
            }
            $item->user;
            $item->order;
        });
        $order = self::$order->where('is_del', 1)->field('name, id')->select();
        return ['data' => $result, 'count' => $count, 'orders' => $order];
    }

    public function getParentProject(){
        $projectModel = new ProjectModel();
        $list = $projectModel->where("pid", "=", "0")->select();
        $returnArr = [];
        if($list)
        {
            foreach ($list as $value)
            {
                $returnArr[$value->id] = $value;
            }
        }
        return $returnArr;
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/9/28
     * Time: 下午9:39
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGd($param)
    {
        // 获取工单表里面最大年份来生成年
        $maxYear = self::$order->max('create_time');
        $year = empty($param['year']) ? 2018 : $param['year'];

        $month = empty($param['month']) ? date('n') : $param['month'];

        // 获取当前月共有多少天
        $total = date('t', strtotime($year.'-'.$month));
        $unit = '号';
        if (empty($param['month'])) {
            $total = 12;
            $unit = '月';
        }
        $yearArr = range($year, empty($maxYear) ? $year : $maxYear);   // 生成年的数组
        $monthArr = range(1, 12); // 生成月的数组
        $dayArr = range(1, $total); // 生成天
        $format = 'month'; // 按月格式化

        $whereTime = ['create_time', [
            $year .'-01-01',
            $year .'-12-31'
        ]];

        // 当前月的所有日期
        $time = [];
        $timeDate = [];
        // 当前年的所有月份
        foreach ($dayArr as $key => $item) {
            $time[$key] = $year . '-' . str_pad($item, 2, '0', STR_PAD_LEFT);
            $timeDate[$key] = $item . $unit;
        }

        if ($param['month']) {
            $whereTime = ['create_time', [
                date('Y-m-d', strtotime($year . '-' . $month . '-'. 01)),
                date('Y-m-d', strtotime($year. '-' . $month . '-' . $total))
            ]];
            $format = 'day'; // 按天
            unset($time);
            unset($timeDate);
            foreach ($dayArr as $key => $item) {
                $time[$key] = date('Y-m-d', strtotime($year . '-' . $month . '-' . $item));
                $timeDate[$key] = $item . $unit;
            }
        }

        // 充电桩交流数量
        $chargeCountOne = $this->chargeType(['a.charge_type' => 1], $whereTime, $format);
        // 充电桩直流数量
        $chargeCountTwo = $this->chargeType(['a.charge_type' => 2], $whereTime, $format);

        // 检测项目合格数
        $detectionCountOne = $this->detectionType(['status' => 1], $whereTime, $format);

        // 检测项目不合数
        $detectionCountTwo = $this->detectionType(['status' => 2], $whereTime, $format);

        // 检测项目总数
        $formatDate = $format == 'day' ? '%Y-%m-%d' : '%Y-%m';
        $detectionCount = self::$orderProject->where($whereTime[0], 'between', $whereTime[1])
            ->fieldRaw('count(*) as num, DATE_FORMAT(`create_time`, "'. $formatDate .'") as create_at')
            ->group('DATE_FORMAT(`create_time`, "'. $formatDate .'")')
            ->select()
            ->toArray();

        $detection_key_time = array_column($detectionCount, 'num', 'create_at');
        $detection_key_one = array_column($detectionCountOne, 'num', 'create_at');
        $detection_key_two = array_column($detectionCountTwo, 'num', 'create_at');
        $charge_key_one = array_column($chargeCountOne, 'num', 'create_at');
        $charge_key_two = array_column($chargeCountTwo, 'num', 'create_at');

        $result = []; // 结果集
        // 把数据拼装到每天
        foreach ($time as $key => $val) {
            $result['detectionCount'][$key] = 0;                // 检测项目总数量
            $result['detectionCountOne'][$key] = 0;             // 检测项目合格量
            $result['detectionCountTwo'][$key] = 0;             // 检测项目不合格量
            $result['chargeCountOne'][$key] = 0;                // 充电桩直流数量
            $result['chargeCountTwo'][$key] = 0;                // 充电桩交流数量

            // 检测项目总数量
            if (array_key_exists($val, $detection_key_time)) {
                $result['detectionCount'][$key] = $detection_key_time[$val];
            }

            // 检测项目合格数量
            if (array_key_exists($val, $detection_key_one)) {
                $result['detectionCountOne'][$key] = $detection_key_one[$val];
            }

            // 检测项目不合格数量
            if (array_key_exists($val, $detection_key_two)) {
                $result['detectionCountTwo'][$key] = $detection_key_two[$val];
            }

            // 充电桩直流数量
            if (array_key_exists($val, $charge_key_one)) {
                $result['chargeCountOne'][$key] = $charge_key_one[$val];
            }

            // 充电桩交流数量
            if (array_key_exists($val, $charge_key_two)) {
                $result['chargeCountTwo'][$key] = $charge_key_two[$val];
            }
        }

        return [
            'yearArr' => $yearArr,
            'dayArr' => !empty($param['month']) ? $dayArr : $monthArr,
            'timeDate' => $timeDate,
            'data' => $result
        ];
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/9/28
     * Time: 下午11:27
     * @param $where
     * @param $whereTime
     * @param $type
     * @return array|\PDOStatement|string|Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function chargeType($where, $whereTime = [], $type = 'day')
    {
        $db = Db::table('charge_pile a')->where($where)
            ->join('orders b', 'a.id = b.charge_id')
            ->where('b.is_del', 1);

        if (!empty($whereTime)) {
            $db = $db->where('b.' .$whereTime[0], 'between', $whereTime[1]);
        }

        $format = $type == 'day' ? '%Y-%m-%d' : '%Y-%m';

        return $db->fieldRaw('count(b.id) as num, DATE_FORMAT(b.`create_time`, "'. $format .'") as create_at')
            ->group('DATE_FORMAT(b.`create_time`, "'. $format .'")')
            ->select()
            ->toArray();
    }

    private function detectionType($where, $whereTime = [], $type = 'day')
    {
        $db = self::$model->where($where);

        if (!empty($whereTime)) {
            $db = $db->where($whereTime[0], 'between', $whereTime[1]);
        }

        $format = $type == 'day' ? '%Y-%m-%d' : '%Y-%m';

        return $db->fieldRaw('count(*) as num, DATE_FORMAT(`create_time`, "'. $format .'") as create_at')
            ->group('DATE_FORMAT(`create_time`, "%Y-%m-%d")')
            ->select()
            ->toArray();
    }

}